<template>
  <div style="margin: 10px">
    <el-card>
      <el-row class="hdRow">
        <el-col :span="24" v-if="!!queryID">试题修改</el-col>
        <el-col :span="24" v-else>试题录入</el-col>
      </el-row>
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef">
        <el-row>
          <el-col :span="8">
            <el-form-item label="学科：" prop="subjectID">
              <el-select v-model="addForm.subjectID" @change="getDirectorysAndTags(addForm.subjectID)">
                <el-option v-for="(item, index) in subjectList" :key="index" :label="item.subjectName" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="目录：" prop="catalogID">
              <el-select v-model="addForm.catalogID">
                <el-option v-for="(item, index) in directorysList" :key="index" :label="item.directoryName" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="企业：" prop="enterpriseID">
              <el-select v-model="addForm.enterpriseID">
                <el-option v-for="(item, index) in companysList" :key="index" :label="item.shortName" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="城市：" prop="province">
              <el-select style="width: 49%; margin-right: 2%" v-model="addForm.province" @change="getCitys">
                <el-option v-for="item in provinces" :key="item.id" :label="item" :value="item"></el-option>
              </el-select>
              <el-select style="width: 49%" v-model="addForm.city">
                <el-option v-for="item in city" :key="item.id" :label="item" :value="item"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="方向：" prop="direction">
              <el-select v-model="addForm.direction">
                <el-option v-for="(item, index) in directionList" :key="index" :label="item.name" :value="item.name"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="题型：">
              <el-radio-group v-model="addForm.questionType">
                <el-radio :label="1">单选</el-radio>
                <el-radio :label="2">多选</el-radio>
                <el-radio :label="3">简答</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="难度：">
              <el-radio-group v-model="addForm.difficulty">
                <el-radio :label="1">简单</el-radio>
                <el-radio :label="2">一般</el-radio>
                <el-radio :label="3">困难</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 题干富文本 -->
        <el-row>
          <el-col :span="24">
            <el-form-item label="题干：" prop="question">
              <quill-editor style="height: 200px" v-model="addForm.question"></quill-editor>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 题目选项区域 -->
        <el-row>
          <el-col :span="24" v-if="addForm.questionType === 1">
            <el-form-item label="选项：" v-for="item in addForm.options" :key="item.index">
              <el-row>
                <el-col :span="1">
                  <el-radio v-model="item.isRight" label="1">{{ String.fromCodePoint(item.code) + '：' }}</el-radio>
                </el-col>
                <el-col :span="5">
                  <el-input v-model="item.title"></el-input>
                </el-col>
                <el-col :span="10">
                  <el-upload
                    class="upload-demo"
                    action="https://jsonplaceholder.typicode.com/posts/"
                    :on-preview="handlePreview"
                    :on-remove="handleRemove"
                    :before-remove="beforeRemove"
                    multiple
                    :limit="3"
                    :on-exceed="handleExceed"
                    :file-list="fileList"
                  >
                    <el-button size="medium" class="optionsBtn">点击上传</el-button>
                  </el-upload>
                </el-col>
              </el-row>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 多选框组 -->
        <el-row>
          <el-col :span="24" v-if="addForm.questionType === 2">
            <el-form-item label="选项：" v-for="item in addForm.options" :key="item.index">
              <el-row>
                <el-col :span="1">
                  <el-checkbox-group v-model="item.isRight">
                    <el-checkbox :label="String.fromCodePoint(item.code) + '：'" @change="logLabel"></el-checkbox>
                  </el-checkbox-group>
                </el-col>
                <el-col :span="5">
                  <el-input v-model="item.title"></el-input>
                </el-col>
                <el-col :span="10">
                  <el-upload
                    class="upload-demo"
                    action="https://jsonplaceholder.typicode.com/posts/"
                    :on-preview="handlePreview"
                    :on-remove="handleRemove"
                    :before-remove="beforeRemove"
                    multiple
                    :limit="3"
                    :on-exceed="handleExceed"
                    :file-list="fileList"
                  >
                    <el-button size="medium" class="optionsBtn">点击上传</el-button>
                  </el-upload>
                </el-col>
              </el-row>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item>
              <el-button type="danger" icon="el-icon-plus" size="small" class="add" v-if="addForm.questionType === 1" disabled>增加选项与答案</el-button>
              <el-button type="danger" icon="el-icon-plus" size="small" class="add" v-else-if="addForm.questionType === 3" style="display: none">增加选项与答案</el-button>
              <el-button type="danger" icon="el-icon-plus" size="small" class="add" v-else @click="addOption">增加选项与答案</el-button>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="解析视频：" style="">
              <el-input v-model="addForm.videoURL"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 答案解析富文本 -->
        <el-row>
          <el-col :span="24">
            <el-form-item label="答案解析： " prop="answer">
              <quill-editor style="height: 200px" v-model="addForm.answer"></quill-editor>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="题目备注：">
              <el-input type="textarea" autocomplete="off" rows="2" placeholder="请输入内容" resize="none" class="tip" v-model="addForm.remarks"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="题目标签：">
              <el-select class="tag" v-model="addForm.tags" multiple filterable allow-create default-first-option placeholder="请选择">
                <el-option v-for="(item, index) in tagsList" :key="index" :label="item.tagName" :value="item.tagName"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item>
          <el-button @click="addNewQuestions" type="primary" v-if="!!queryID">确认修改</el-button>
          <el-button @click="addNewQuestions" type="primary" v-else>确认提交</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { provinces, citys } from './citys'
import _ from 'lodash'
export default {
  name: 'questions-new',
  data () {
    return {
      queryID: null,
      // 试题录入表单
      addForm: {
        subjectID: '', // 学科
        catalogID: '', // 目录
        enterpriseID: '', // 企业
        province: '', // 城市
        city: '', // 地区
        direction: '', // 方向
        questionType: 1, // 题型
        difficulty: 1, // 难度
        question: '', // 题干
        options: [
          { code: 65, img: '', isRight: 0, title: '' },
          { code: 66, img: '', isRight: 0, title: '' },
          { code: 67, img: '', isRight: 0, title: '' },
          { code: 68, img: '', isRight: 0, title: '' }
        ],
        // 选项
        videoURL: '', // 解析视频
        answer: '', // 答案解析
        remarks: '', // 题目备注
        tags: [] // 试题标签
      },
      fileList: [], // 存放文件路径
      province: '',
      // 表单验证规则
      addFormRules: {
        subjectID: [{ required: true, message: '请选择学科！', trigger: 'change' }],
        catalogID: [{ required: true, message: '请选择目录！', trigger: 'change' }],
        enterpriseID: [{ required: true, message: '请选择企业！', trigger: 'change' }],
        province: [{ required: true, message: '请选择城市！', trigger: 'change' }],
        direction: [{ required: true, message: '请选择方向！', trigger: 'change' }],
        question: [
          { required: true, message: '请填写题干！', trigger: 'blur' }
        ],
        answer: [
          { required: true, message: '请填写答案解析！', trigger: 'blur' }
        ]
      },
      subjectList: [], // 学科列表
      directorysList: [], // 根据选中的学科获取的目录列表
      companysList: [], // 企业列表
      tagsList: [], // 标签列表
      provinces: provinces(), // 城市列表
      city: [], // 地区列表
      directionList: [
        { name: 'o2o' },
        { name: '外包服务' },
        { name: '企业服务' },
        { name: '互联网金融' },
        { name: '企业咨询' },
        { name: '互联网' },
        { name: '电子商务' },
        { name: '其他' }],
      // 方向
      citys
    }
  },
  created () {
    this.getSubject()
    this.getCompanys()
    this.getP()
  },
  methods: {
    getCitys (value) {
      this.addForm.city = ''
      this.city = this.citys(value)
    },
    // 根据携带的ID获取试题详情
    async getQtdata () {
      const res = await this.$http.get(`/questions/${this.queryID}`)
      if (res.status !== 200) return this.$message.error('获取数据失败！')
      console.log(res.data)
      var newData = _.cloneDeep(res.data)
      newData.difficulty = Number(newData.difficulty)
      newData.questionType = Number(newData.questionType)
      newData.tags = newData.tags.split(',')
      // console.log(newData)
      this.addForm = newData
      console.log(this.addForm)
    },

    // editData () {
    //   if(this.addForm.questionType&&this.addForm.difficulty)
    // },
    // 获取学科列表
    async getSubject () {
      this.queryID = this.$route.query.id
      // console.log(this.queryID.length)
      const res = await this.$http.get('/subjects', { params: { pagesize: 50 } })
      if (res.status !== 200) return this.$message.error('获取数据失败')
      this.subjectList = res.data.items
      if (this.queryID) {
        this.getQtdata()
      }
    },
    // console.log(this.subjectList)

    // 根据选中的学科获取目录列表和获取标签列表
    async getDirectorysAndTags (id) {
      const res = await this.$http.get('/directorys', { params: { subjectID: id } })
      // console.log(res)
      if (res.status !== 200) return this.$message.error('获取数据失败！')
      this.directorysList = res.data.items
      console.log(this.directorysList)

      const res2 = await this.$http.get('/tags', { params: { subjectID: id, state: 1 } })
      if (res.status !== 200) return this.$message.error('获取标签数据失败！')
      this.tagsList = res2.data.items
    },
    // 获取企业列表
    async getCompanys () {
      const res = await this.$http.get('/companys', { params: { pagesize: 50 } })
      if (res.status !== 200) return this.$message.error('获取数据失败！')
      this.companysList = res.data.items
      // console.log(this.companysList)
    },
    // 确认提交按钮
    addNewQuestions () {
      this.$refs.addFormRef.validate(async valid => {
        /*eslint-disable*/
        if (!valid) {
          this.$message.error('请填写合法的数据项')
          return
        }
        const newAddForm = _.cloneDeep(this.addForm)
        newAddForm.tags = newAddForm.tags.join(',')
        newAddForm.options.forEach(item => {
          if (item.code) {
            item.code = String.fromCodePoint(item.code)
          }
          if (item.isRight === true) {
            item.isRight === 1
          } else if (item.isRight === false) {
            item.isRight === 1
          } else {
            item.isRight === item.isRight
          }
        })
        newAddForm.difficulty = String(newAddForm.difficulty)
        newAddForm.questionType = String(newAddForm.questionType)
        console.log(newAddForm);
        // 判断是否有携带参数，有则是修改，无则是添加
        if (this.queryID) {
          const res = await this.$http.put(`/questions/${this.queryID}`)
          if (res.status !== 200) return this.$message.error('修改失败！')
          this.$message.success('修改试题成功！')
          this.$refs.addFormRef.resetFields()
          this.$router.push({ path: '/questions/list' })
        } else {
          const res = await this.$http.post('/questions', newAddForm)
          if (res.status !== 200) return this.$message.error('添加试题失败！')
          this.$message.success('添加试题成功！')
          this.$refs.addFormRef.resetFields()
          this.$router.push({ path: '/questions/list' })
        }

      })
    },
    selectOption (e) {
      console.log(e);
    },
    // 增加选项按钮功能
    addOption () {
      // console.log(this.multipleChoice);
      var num = this.addForm.options[this.addForm.options.length - 1].code
      num++
      console.log(num);
      var option = { code: num, img: '', isRight: 0, title: '' }
      this.addForm.options.push(option)
      // this.multipleChoice.push(num)
      console.log(this.addForm.options)
    },
    // 上传
    handleRemove (file, fileList) {
      console.log(file, fileList);
    },
    handlePreview (file) {
      console.log(file);
    },
    handleExceed (files, fileList) {
      this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    beforeRemove (file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    async getP () {
      const res = await this.$http.get('/questions', { params: { pagesize: 50 } })
      // console.log(res.data)
    },
    logLabel (e) {
      // console.log(e)
      // console.log(this.addForm.options)
    }
  },
  computed: {
  }
}
</script>

<style scoped lang="less">
/deep/.hdRow {
  height: 58px;
  line-height: 58px;
  border-bottom: 1px solid #9a9a9a;
  box-sizing: border-box;
  /deep/ el-col {
    margin: 20px 0;
  }
}
.el-form {
  margin: 30px 0 0 0px;
  .el-form-item {
    margin-bottom: 10px;
  }
  /deep/.el-form-item__label {
    width: 120px;
    margin: 0 0px 3px 0;
  }
  /deep/.el-form-item__content {
    margin: 0 0 10px 120px;
  }
  .el-select {
    width: 100%;
  }
  .add {
    margin: 20px 0 0 0px;
  }

  .tip {
    width: 100%;
    // transform: translateX(-20px);
  }
}
.el-input {
  width: 100%;
  // transform: translateX(-20px);
}
.quill-editor {
  margin: 0 0 60px 0px;
}
// .tag {
//   // transform: translateX(-20px);
// }
.optionsBtn {
  height: 50px;
  margin-left: 10px;
  transform: translateY(-6px);
}
</style>
